<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\model\DistributionRecord;
use think\facade\Db;

class DistributionSettlementController
{
    /**
     * 分销结算
     */
    public function settle()
    {
        $merchantId = request()->merchant_id;
        $recordIds = input('record_ids/a');
        
        if (empty($recordIds)) {
            return json(['code' => 1, 'msg' => '请选择要结算的记录']);
        }

        Db::startTrans();
        try {
            // 获取待结算记录
            $records = DistributionRecord::where([
                'merchant_id' => $merchantId,
                'status' => DistributionRecord::STATUS_PENDING
            ])->whereIn('id', $recordIds)->select();

            if ($records->isEmpty()) {
                throw new \Exception('没有可结算的记录');
            }

            foreach ($records as $record) {
                // 更新分销记录状态
                $record->status = DistributionRecord::STATUS_SETTLED;
                $record->save();

                // 给用户增加余额
                $user = \app\model\User::find($record->user_id);
                $user->balance += $record->commission;
                $user->save();

                // 记录用户余额变动
                \app\model\UserBalanceFlow::create([
                    'merchant_id' => $merchantId,
                    'user_id' => $record->user_id,
                    'type' => 5, // 分销佣金
                    'amount' => $record->commission,
                    'balance_before' => $user->balance - $record->commission,
                    'balance_after' => $user->balance,
                    'remark' => "分销佣金结算 订单:{$record->order_no}"
                ]);
            }

            Db::commit();
            return json(['code' => 0, 'msg' => '结算成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 批量失效
     */
    public function invalid()
    {
        $merchantId = request()->merchant_id;
        $recordIds = input('record_ids/a');
        
        if (empty($recordIds)) {
            return json(['code' => 1, 'msg' => '请选择要操作的记录']);
        }

        try {
            DistributionRecord::where([
                'merchant_id' => $merchantId,
                'status' => DistributionRecord::STATUS_PENDING
            ])->whereIn('id', $recordIds)
              ->update(['status' => DistributionRecord::STATUS_INVALID]);

            return json(['code' => 0, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 